package com.seventh.tickets.service.Impl;

import com.seventh.tickets.entity.User;
import com.seventh.tickets.entity.UserDetail;
import com.seventh.tickets.repository.UserDetailRepository;
import com.seventh.tickets.repository.UserRepository;
import com.seventh.tickets.service.UserDetailService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserDetailServiceImpl implements UserDetailService {

    private final UserDetailRepository userDetailRepository;
    private final UserRepository userRepository;

    public UserDetailServiceImpl(UserDetailRepository userDetailRepository, UserRepository userRepository) {
        this.userDetailRepository = userDetailRepository;
        this.userRepository = userRepository;
    }

    /**
     * 获取用户详细信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserDetail getUserById(Long userId) {
        return userDetailRepository.findByUserId(userId);
    }

    @Override
    public UserDetail getUserDetail(String userLoginName) {
        return userDetailRepository.findByUserLoginName(userLoginName);
    }


    @Override
    public UserDetail updateUserDetail(String userLoginName, String userName, String userPhone, String userLivePlace, String userEmail, String userIdCard) throws Exception {

        if (userLoginName == null || userName == null || userPhone == null || userLivePlace == null || userEmail == null || userIdCard == null) {
            throw new Exception("修改用户信息数据不完整");
        } else {
            UserDetail userDetail = userDetailRepository.findByUserLoginName(userLoginName);
            User user = userRepository.findByUserLoginName(userLoginName);
            if (userDetail == null) {
                throw new Exception("未查到该用户信息");
            } else {
                userDetail.setUser(user);
                userDetail.setUserName(userName);
                userDetail.setUserPhone(userPhone);
                userDetail.setUserLivePlace(userLivePlace);
                userDetail.setUserEmail(userEmail);
                userDetail.setUserIdCard(userIdCard);
                UserDetail userDetail1 = userDetailRepository.save(userDetail);
                if (userDetail1.getDetailId() > 0) {
                    return userDetail1;
                } else {
                    throw new Exception("修改用户信息失败！");
                }
            }
        }
    }

    /**
     * 更新用户详细信息
     *
     * @param entity UserDetail
     * @return
     */
    @Override
    public UserDetail updateUserDetail(UserDetail entity) {
        return userDetailRepository.saveAndFlush(entity);
    }
}
